// 引入express服务器
const express = require('express');
const pool = require('../pool');
// 创建路由器对象
const addr = express.Router();

// -------------------1.新增地址信息------------------------
addr.post("/add", (req, res, next) => {
  var obj = req.body;
  console.log(obj);
     let sql = "INSERT INTO user_addrs (user_id,receiver,cellphone,province,city,area,areacode,addr,is_default) VALUES (?,?,?,?,?,?,?,?,?)";
     pool.query(sql, [obj.user_id,obj.receiver,obj.cellphone,obj.province,obj.city,obj.area,obj.areacode,obj.addr,obj.is_default], (err, result) => {
        if (err) {
            next(err);
            return;
          }
        res.send({
          code: 200,
          msg:'添加成功'
        })
    })
})
// -------------------2.删除地址信息---------------------
addr.delete("/delete/:did", (req, res, next) => {
  var obj = req.params;
  console.log(obj)
  let sql = "DELETE FROM user_addrs WHERE did=?";
  pool.query(sql, [obj.did], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 200,
      msg:'删除成功'
    })
  })
})

// -------------------3.地址更新信息---------------------
addr.post("/update",(req,res,next)=>{
  var obj = req.body;
  let sql = "UPDATE user_addrs SET receiver=?,cellphone=?,areacode=? WHERE did=?";
  pool.query(sql, [obj.receiver,obj.cellphone,obj.areacode,obj.did], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 200,
      msg:'更新成功'
    })
  })
})

// ---------------4.查询相关用户的所有地址信息------------------
addr.post("/", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  let sql = 'SELECT * FROM user_addrs WHERE user_id=?';
  pool.query(sql,[obj.user_id], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '查询失败',
      });
    } else {
      res.send({
        code: 200,
        msg: '查询成功',
        data: result,
      });
    }
  })
})
// ---------------5.查询地址信息------------------
addr.post("/details", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  let sql = 'SELECT * FROM user_addrs WHERE did=?';
  pool.query(sql,[obj.did], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '查询失败',
      });
    } else {
      res.send({
        code: 200,
        msg: '查询成功',
        data: result,
      });
    }
  })
})
// 导出路由器对象
module.exports = addr;